﻿using System.Linq;
using ModulesToolkit.DataContracts;

namespace ModulesToolkit.DataAccess.Membership
{
    using System.Data.Common;
    using System.Data.SqlClient;
    using Microsoft.Practices.EnterpriseLibrary.Data;
    using ModulesToolkit.DataContracts.Membership;

    /// <summary>
    /// Create Read operations for read only entities from the database
    /// </summary>
    /// <author>
    /// Mina
    /// </author>
    public class UsersDtoRepository
    {
        #region Methods

        /// <summary>
        /// Retrieves the users.
        /// </summary>
        /// <param name="searchCriteria">The search criteria.</param>
        /// <returns></returns>
        public EntitySearchResult<UserDto> RetrieveUsers(UserDtoSearchCriteria searchCriteria)
        {
            Database database = DatabaseFactory.CreateDatabase();
            using (DbCommand command = database.GetStoredProcCommand("[Membership].[RetrieveUsers]"))
            {
                try
                {
                    return new EntitySearchResult<UserDto>(
                        database.Execute<UserDto>(command, searchCriteria.AsParameters().ToArray()).ToList(),
                        database.GetParameterValue(command, "RETURN_VALUE").ConvertTo<int>().GetValueOrDefault()
                        );
                }
                catch (SqlException exception)
                {
                    throw exception.Translate();
                }
            }
        }

        #endregion Methods

        public void DeleteUser(int id)
        {
            Database database = DatabaseFactory.CreateDatabase();
            database.ExecuteNonQuery("[Membership].[DeleteUser]", id);
        }
    }
}